<template>
  <div class="drawer-box">
    <el-drawer v-model="showWorkConfirm">
      <!--    start header-->
      <template #header>
        <div class="drawer-header">
          <title-view title="开工确认" />
        </div>
      </template>
      <!--    end header-->
      <!--    start drawer-content-->
      <div class="drawer-content" v-loading="isLoading">
        <!--        start left-content-->
        <div class="left-content">
          <div class="work-information">
            <div class="gray-background">
              <div class="contract-situation">
                <div class="title">合同准备情况<span v-if="isShowContractTips">（当前合同未完签约，无法申请开工）</span></div>
                <div class="material-list">
                  <!-- 1 完成合同，2 未完成合同-->
                  <div class="material-item" v-for="contractItem in detailInfo.contracts">
                    <div class="material-item__text" :class="{ 'material-item--disabled': contractItem.contractStatus === 2 }">
                      {{ contractItem.contractName }}
                    </div>
                    <svg-icon v-if="contractItem.contractStatus === 1" iconClass="gray-select" style="font-size: 14px" />
                  </div>
                  <div class="no-data" v-if="detailInfo.contracts?.length == 0">暂无数据</div>
                </div>
              </div>
              <div class="information-situation" v-if="detailInfo.contractDatas?.length">
                <div class="title">资料准备情况<span v-if="isShowMaterialTips">（当前资料准备不全，强制开工需要审批）</span></div>
                <div class="material-list">
                  <div class="material-item" v-for="materialItem in detailInfo.contractDatas">
                    <div class="material-item__text" :class="{ 'material-item--disabled': materialItem.dataStatus === 2 }">
                      {{ materialItem.dataName }}
                    </div>
                    <svg-icon
                      v-if="materialItem.dataStatus === 1"
                      iconClass="gray-select"
                      style="font-size: 14px; flex-shrink: 0"
                    />
                  </div>
                </div>
              </div>
            </div>
            <el-form ref="formRef" :model="formData" :rules="addFormRules">
              <el-form-item label="实际开工时间" prop="factStartDate">
                <el-date-picker
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  v-model="formData.factStartDate"
                  type="date"
                  placeholder="请选择时间"
                  style="width: 100%"
                  @change="handleChangeDate"
                />
                <div class="contract-time">
                  <div class="contract-time__duration">
                    <el-tooltip v-if="detailInfo.contractDurations?.length" effect="light" placement="bottom-start">
                      <el-icon style="cursor: pointer"><QuestionFilled size="16" color="#858F9B" /></el-icon>
                      <template #content>
                        <span style="padding-right: 10px" v-for="item in detailInfo.contractDurations"
                          >{{ item.durationName }}:{{ item.durationType === 1 ? "+" : "-" }}{{ item.durationDays }}天</span
                        >
                      </template>
                    </el-tooltip>
                    合同工期(总)：{{
                      detailInfo.contractDurations?.length
                        ? detailInfo.totalContractDuration + "天"
                        : "按流程配置的标准天数自动计算"
                    }}
                  </div>
                  <div class="contract-time__complete">合同完工时间：{{ formData.plainEndDate }}</div>
                </div>
                <div class="contract-tips">若开工前需变更，请在客户详情页发起售后变更单进行处理！</div>
              </el-form-item>
              <el-form-item>
                <!--      附件上传 start    -->
                <file-upload :fileList="fileList" :maxSize="100" @uploadSuccess="uploadSuccess" @uploadRemove="uploadRemove" />
                <!--       附件上传 end   -->
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="formData.remark"
                  style="width: 100%"
                  :autosize="{ minRows: 3 }"
                  type="textarea"
                  placeholder="请输入注意事项和备注信息（内部查看）"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!--        end left-content-->
        <!--        start right-content-->
        <div class="right-content">
          <process-technology
            v-model="processTechnologyList"
            @on-confrim="getProcessList"
            v-if="currentType === acceptancePlanType.ACCEPTANCE_TEMPLATE"
          ></process-technology>
          <template v-else>
            <div class="no-data__title">请进行工序工艺确认</div>
            <el-empty />
          </template>
          <work-purchase v-model="purchaseList" />
        </div>
        <!--        end right-content-->
      </div>
      <!--    end drawer-content-->
      <template #footer>
        <div class="button-action">
          <el-button color="#F2F3F5" @click="handleCancel">取消</el-button>
          <el-button color="#007DFF" :disabled="isLoading" @click="handleConfirm">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, ref } from "vue";
import { useRoute } from "vue-router";
import { getAcceptanceList } from "@/apis/clientManager";
import { workConfirmDetail, startWorkConfirm, completionDate } from "@/apis/constructionPlan";
import { QuestionFilled } from "@element-plus/icons-vue";
import FileUpload from "@/components/FileUpload";
import ProcessTechnology from "../components/ProcessTechnology.vue";
import WorkPurchase from "@/components/WorkPurchase";

const route = useRoute();
const customerId = route.query.customerId;

const acceptancePlanType = {
  ACCEPTANCE: 1, //商家验收
  ACCEPTANCE_TEMPLATE: 0 //商家验收标准模版
};

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:modelValue", "workApplySave"]);
const showWorkConfirm = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

const initFormData = {
  customerId,
  factStartDate: "",
  businessChecks: [],
  remark: "",
  plainEndDate: "--"
};
const formData = ref({ ...initFormData });
const isLoading = ref(false);
const addFormRules = {
  factStartDate: { required: true, message: "请选择实际开工时间", trigger: "change" }
};

//时间
const handleChangeDate = async () => {
  const { factStartDate } = formData.value;
  const res = await completionDate(customerId, { date: factStartDate });
  formData.value.plainEndDate = res?.data;
};

//文件
const fileList = ref([]);
const uploadSuccess = fileObj => {
  fileList.value.push(fileObj);
};
const uploadRemove = index => {
  fileList.value.splice(index, 1);
};

//工序工艺
const processTechnologyList = ref([]);
const currentType = ref(null);
const setDefaultSelection = list => {
  list?.forEach(item => {
    item.children?.forEach(child => {
      const defaultChild = child.children?.find(grandChild => grandChild.isDefault === 1);
      if (defaultChild) {
        child.selectedVal = defaultChild.standardId;
      }
    });
  });
};
const getProcessList = async () => {
  try {
    const { data } = await getAcceptanceList(customerId);
    currentType.value = data?.type ?? 1;
    if (currentType.value === acceptancePlanType.ACCEPTANCE_TEMPLATE) {
      let treeSelectList = data?.treeSelectList ?? [];
      setDefaultSelection(treeSelectList);
      processTechnologyList.value = treeSelectList;
    }
  } catch (err) {}
};

//获取详情
const purchaseList = ref([]);
const detailInfo = ref({});
const getDetail = async () => {
  const { data } = await workConfirmDetail(customerId);
  detailInfo.value = data;
  let stageTaskSettingList = data?.stageTaskSettingList ?? [];
  let customerMaterialSelfBuyRecords = data?.customerMaterialSelfBuyRecords ?? [];
  stageTaskSettingList =
    stageTaskSettingList.length &&
    stageTaskSettingList.map(item => {
      item.isCustomerBuy = 0;
      return Object.assign(
        item,
        customerMaterialSelfBuyRecords.find(selectItem => {
          if (item.taskSettingId === selectItem.taskSettingId) {
            item.isCustomerBuy = 1;
            item.buyRemark = selectItem.buyRemark;
          }
        })
      );
    });
  purchaseList.value = stageTaskSettingList;
};
const isShowContractTips = computed(() => {
  const contracts = detailInfo.value.contracts ?? [];
  if (contracts.length) {
    const filterNotComplete = contracts.filter(item => item.contractStatus === 2);
    return filterNotComplete.length > 0;
  } else {
    return true;
  }
});
const isShowMaterialTips = computed(() => {
  const contractDatas = detailInfo.value.contractDatas ?? [];
  if (contractDatas.length) {
    const filterNotComplete = detailInfo.value.contractDatas.filter(item => item.dataStatus === 2);
    return filterNotComplete.length > 0;
  }
});

//按钮操作
const handleConfirm = () => {
  proxy.$refs.formRef.validate(async val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    if (!checkProcessTechnology()) {
      return proxy.$modal.msgError("请填写工序工艺");
    }
    const files = fileList.value.map(item => {
      return {
        name: item.fileName,
        url: item.fileUrl
      };
    });
    let filterPurchaseList = [];
    if (purchaseList.value.length) {
      filterPurchaseList = purchaseList.value.filter(item => item.isCustomerBuy == 1);
    }
    formData.value.customerMaterialSelfBuyRecords = filterPurchaseList;
    formData.value.files = files;
    isLoading.value = true;
    const res = await startWorkConfirm(formData.value);
    isLoading.value = false;
    proxy.$modal.msgSuccess(res?.msg ?? "操作成功");
    setTimeout(() => {
      showWorkConfirm.value = false;
      emit("workConfirmSave");
    }, 1000);
  });
};
const checkProcessTechnology = () => {
  formData.value.businessChecks = [];
  let count = 0;
  processTechnologyList.value.forEach(item => {
    item.children?.forEach(subItem => {
      count++;
      subItem.selectedVal && formData.value.businessChecks.push({ craftId: subItem.selectedVal });
    });
  });
  return count == formData.value.businessChecks.length;
};
const handleCancel = () => {
  formData.value = { ...initFormData };
  processTechnologyList.value = [];
  showWorkConfirm.value = false;
};

getProcessList();
getDetail();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
:deep(.el-drawer) {
  @include mixin.flex-column;
  width: 840px !important;
  border-radius: 20px 0 0 20px;
  .el-drawer__header {
    border-bottom: 1px solid #dcdfe6;
    padding: 0;
    margin-bottom: 0px;
  }
  .el-drawer__close-btn {
    margin-right: 20px;
  }
  .el-drawer__body {
    padding: 0px;
  }
  .el-drawer__footer {
    padding: 0px;
  }
}

.title {
  font-size: 14px;
  font-weight: bold;
  color: #3d3d3d;
  margin-bottom: 10px;
  span {
    font-size: 12px;
    color: #ea0000;
    font-weight: normal;
  }
}
.drawer-box {
  .drawer-header {
    padding: 20px;
  }
  .drawer-content {
    @include mixin.flex;
    height: 100%;

    .left-content {
      width: 50%;
      overflow-y: hidden;
      box-sizing: border-box;
      border-right: 1px solid #dcdfe6;
      .gray-background {
        background-color: #f6f8fa;
        padding: 20px;
        margin-bottom: 20px;
      }
      .work-information {
        height: 100%;
        overflow-y: auto;
        padding: 16px;
        box-sizing: border-box;
        .base-info {
          padding-bottom: 20px;
          margin-bottom: 20px;
          &__item {
            display: flex;
            justify-content: space-between;
            .label {
              color: #86909c;
              flex-shrink: 0;
            }
            .val {
              color: #1a1a1a;
              width: 50%;
              text-align: right;
            }
          }
        }
      }
      .base-info {
        border-bottom: 1px solid #dcdfe6;
        &__item {
          & + .base-info__item {
            margin-top: 17px;
          }
        }
      }
      .contract-situation {
        margin-bottom: 20px;
      }
      .material-list {
        .material-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          &__text {
            font-size: 14px;
            color: #3d3d3d;
            width: 80%;
          }
          &--disabled {
            color: #86909c;
          }
        }
      }
      :deep(.el-form) {
        flex-grow: 1;
        .el-form-item {
          display: block;
        }
        .el-form-item__label {
          color: #86909c;
          font-size: 14px;
          width: 100%;
          display: block;
        }
        .el-input__wrapper,
        .el-textarea__inner {
          background: #f2f3f5;
          color: #86909c;
          box-shadow: none;
        }
        .el-checkbox__label {
          color: #191919;
        }
      }
      .contract-time {
        width: 100%;
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        color: #3d3d3d;
        margin-top: 5px;
        flex-wrap: wrap;
        border: 1px solid #f2f3f5;
        border-radius: 4px;
        padding: 0 10px;
        &__duration {
          display: flex;
          align-items: center;
          :deep(.el-icon) {
            margin-right: 5px;
          }
        }
      }
      .contract-tips {
        font-size: 12px;
        color: #86909c;
      }
    }
    .right-content {
      width: 50%;
      overflow-y: auto;
      padding: 15px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      position: relative;
      .no-data__title {
        font-size: 18px;
        color: #131414;
      }
    }
  }
  .button-action {
    text-align: right;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 15px;
    button {
      width: 120px;
      height: 36px;
    }
  }
}
</style>
